package ${package}.${rootArtifactId}.common.util;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

/**
 * json工具类
 *
 * @author weidong.lin
 * @date 2021/7/9 17:19
 */
public class JsonUtil {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    static {
        // 如果json中有新增的字段并且是实体类类中不存在的，不报错
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    private JsonUtil() {
    }

    /**
     * 转json
     *
     * @param obj
     * @return {@link java.lang.String}
     */
    public static String toJson(Object obj) {
        try {
            if (obj != null) {
                return OBJECT_MAPPER.writeValueAsString(obj);
            }
            return "";
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 对象间转化
     *
     * @param obj
     * @param t
     * @param <T>
     * @return
     */
    public static <T> T transform(Object obj, Class<T> t) {
        return toObject(JSON.toJSONString(obj), t);
    }

    /**
     * array反序列化为对象
     *
     * @param json
     * @param type
     * @return {@link T}
     */
    public static <T> T toObject(String json, TypeReference<T> type) {
        try {
            if (json != null) {
                return OBJECT_MAPPER.readValue(json, type);
            }
            return null;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将json string反序列化成对象
     *
     * @param json
     * @param clazz
     * @return {@link T}
     */
    public static <T> T toObject(String json, Class<T> clazz) {
        try {
            if (json != null) {
                return OBJECT_MAPPER.readValue(json, clazz);
            }
            return null;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将json数据转换成pojo对象list
     *
     * @param jsonData
     * @param beanType
     * @return {@link List <T>}
     */
    public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
        try {
            JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
            if (jsonData != null) {
                return OBJECT_MAPPER.readValue(jsonData, javaType);
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
